package com.weimin.app3.config;


import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.weimin.app3.pojo.RestResp;
import feign.Response;
import feign.Util;
import feign.codec.Decoder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.lang.reflect.Type;

@Slf4j
@RequiredArgsConstructor
public class ResultFeignDecoder implements Decoder {

    private final ObjectMapper objectMapper;

    @Override
    public Object decode(Response response, Type type) throws IOException {
        log.info("调用自定义Feign解码器");

        // 读取响应中数据，将响应体中数据转为字符串
        String bodyString = Util.toString(response.body().asReader());

        // 解析响应体字符串到 Result 对象
        JavaType parameterType = objectMapper.getTypeFactory().constructType(type);
        JavaType resultType = objectMapper.getTypeFactory().constructParametricType(RestResp.class, parameterType);
        RestResp<?> result = objectMapper.readValue(bodyString, resultType);

        // 如果响应状态为失败，抛出业务异常
        if ("-1".equals(result.getCode())) {
            throw new RuntimeException(result.getMsg());
        }

        // 从 Result 中提取 data 字段
        return result.getData();
    }

}